<template>
  <a-card>
    <a-spin :spinning="spinning" size="large">
      <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
        <a-form-item label="所属权益包" has-feedback>
          <a-select
            v-decorator="['memberCardId', { rules: [{ required: true, message: '请选择所属会员卡!' }] }]"
            placeholder="请选择"
            show-search
            :filter-option="filterOption"
            :getPopupContainer="triggerNode => triggerNode.parentNode"
          >
            <a-select-option v-for="(item, index) in goodsList" :key="index" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="权益名称" has-feedback>
          <a-input
            v-decorator="[
              'name',
              {
                rules: [
                  {
                    required: true,
                    max: 20,
                    message: '请输入权益名称，不超过20个字符,不可输入符号！',
                    whitespace: true,
                    pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/
                  }
                ]
              }
            ]"
            name="name"
            placeholder="请输入"
            :max-length="20"
            autocomplete="off"
          />
        </a-form-item>
        <a-row>
          <a-col :lg="5" :sm="7" style="float: left">
            <a-form-item label="生效时间" :labelCol="{ lg: { span: 24 }, sm: { span: 24 } }" :required="true"></a-form-item>
          </a-col>
          <a-col :lg="13" :sm="10">
            <div class="rules-package">
              <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }">
                <a-select
                  v-decorator="['effectiveTime', { rules: [{ required: true, message: '请选择!' }] }]"
                  placeholder="请选择"
                  style="width: 200px; margin-right: 8px"
                  show-search
                  :filter-option="filterOption"
                  @change="handleEffectChange"
                  :getPopupContainer="triggerNode => triggerNode.parentNode"
                >
                  <a-select-option :value="0">开卡即生效</a-select-option>
                  <a-select-option :value="1">开卡后N天生效</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }" v-if="hasEffect">
                <a-input-number v-decorator="['effectiveTimeNum', { rules: [{ required: hasEffect, message: `请输入` }] }]" :step="1" :min="0" placeholder="发放N天后生效" style="width: 200px" />
                天
              </a-form-item>
            </div>
          </a-col>
        </a-row>
        <a-row>
          <a-col :lg="5" :sm="7" style="float: left">
            <a-form-item label="适用商家类型" :labelCol="{ lg: { span: 24 }, sm: { span: 24 } }" :required="true"></a-form-item>
          </a-col>
          <a-col :lg="13" :sm="10">
            <div class="rules-package">
              <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }">
                <a-select
                  v-decorator="['suitableStoreType', { rules: [{ required: true, message: '请选择!' }] }]"
                  placeholder="请选择"
                  style="width: 200px; margin-right: 8px"
                  show-search
                  :filter-option="filterOption"
                  @change="handleStoreChange"
                  :getPopupContainer="triggerNode => triggerNode.parentNode"
                >
                  <a-select-option :value="1">直营可用</a-select-option>
                  <a-select-option :value="2">经销可用</a-select-option>
                  <a-select-option :value="3">直营经销均可用</a-select-option>
                  <a-select-option :value="4">自定义</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }" v-if="customStore">
                <a-select v-decorator="['isStoreId', { rules: [{ required: customStore, message: '请选择!' }] }]" style="width: 100px; margin-right: 8px">
                  <a-select-option :value="1">门店ID</a-select-option>
                  <a-select-option :value="2">门店编码</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }" v-if="customStore">
                <a-input
                  v-decorator="['storeIds', { rules: [{ required: customStore, message: '请输入门店id,请勿输入空格！', pattern: /^[^\s]*$/ }] }]"
                  placeholder="请输入门店id，使用,拼接"
                  name="name"
                  autocomplete="off"
                  style="width: 300px"
                />
              </a-form-item>
            </div>
          </a-col>
        </a-row>
        <a-form-item label="权益类型" has-feedback>
          <a-select
            v-decorator="['rightsType', { rules: [{ required: true, message: '请选择权益类型！' }] }]"
            placeholder="请选择"
            @change="handleSelectChange"
            :getPopupContainer="triggerNode => triggerNode.parentNode"
          >
            <a-select-option :value="item.rightType" v-for="(item, index) in rightConfig" :key="index">
              {{ item.groupName }}
            </a-select-option>
            <!-- <a-select-option value="2">
              预售盒子
            </a-select-option>
            <a-select-option value="3">
              展示权益
            </a-select-option> -->
          </a-select>
        </a-form-item>
        <!-- 生日优惠券 配置时间 -->
        <template v-if="this.typeRules.rightType == 6">
          <a-row v-show="this.typeRules.rightType == 6">
            <a-col :lg="5" :sm="7" style="float: left">
              <a-form-item label="开始领取时间" :labelCol="{ lg: { span: 24 }, sm: { span: 24 } }" :required="true"></a-form-item>
            </a-col>
            <a-col :lg="13" :sm="10">
              <div class="rules-package">
                <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }">
                  <a-select
                    v-decorator="['startDrawTimeConfigType', { rules: [{ required: true, message: '请选择!' }] }]"
                    placeholder="请选择"
                    style="width: 240px; margin-right: 8px"
                    show-search
                    :filter-option="filterOption"
                    @change="e => handleBirthdayChange(e, 'start')"
                    :getPopupContainer="triggerNode => triggerNode.parentNode"
                  >
                    <a-select-option value="0">生日月1号开始领取</a-select-option>
                    <a-select-option value="1">生日月前N天开始领取</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }" v-if="getStartDays">
                  <a-input-number
                    v-decorator="['startDrawTimeConfigNum', { rules: [{ required: getStartDays, message: `请输入` }] }]"
                    :step="1"
                    :min="0"
                    placeholder="生日月前N天开始领取"
                    style="width: 200px"
                  />
                  天
                </a-form-item>
              </div>
            </a-col>
          </a-row>
          <a-row v-show="this.typeRules.rightType == 6">
            <a-col :lg="5" :sm="7" style="float: left">
              <a-form-item label="结束领取时间" :labelCol="{ lg: { span: 24 }, sm: { span: 24 } }" :required="true"></a-form-item>
            </a-col>
            <a-col :lg="13" :sm="10">
              <div class="rules-package">
                <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }">
                  <a-select
                    v-decorator="['endDrawTimeConfigType', { rules: [{ required: true, message: '请选择!' }] }]"
                    placeholder="请选择"
                    show-search
                    style="width: 240px; margin-right: 8px"
                    @change="e => handleBirthdayChange(e, 'end')"
                    :filter-option="filterOption"
                    :getPopupContainer="triggerNode => triggerNode.parentNode"
                  >
                    <a-select-option value="0">生日月最后一天结束领取</a-select-option>
                    <a-select-option value="1">生日月后N天结束领取</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }" v-if="getEndDays">
                  <a-input-number
                    v-decorator="['endDrawTimeConfigNum', { rules: [{ required: getEndDays, message: `请输入` }] }]"
                    :step="1"
                    :min="0"
                    placeholder="生日月后N天结束领取"
                    style="width: 200px"
                  />
                  天
                </a-form-item>
              </div>
            </a-col>
          </a-row>
        </template>
        <!-- 生日优惠券 配置时间 -->
        <template v-if="typeRules.children">
          <a-row style="">
            <a-col :lg="5" :sm="7" style="float: left">
              <a-form-item :label="typeRules.groupName" :labelCol="{ lg: { span: 24 }, sm: { span: 24 } }" :required="true"></a-form-item>
            </a-col>
            <a-col :lg="18" :sm="10">
              <div v-for="(child, childIndex) in typeRules.children" :key="childIndex" class="rules-package">
                <a-form-item v-for="(subItem, subIndex) in child" :key="subIndex" :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }">
                  <template v-if="subItem.formType == 'input'">
                    <a-input
                      v-decorator="[
                        `useRule[${childIndex}][${subItem.name}]`,
                        { initialValue: useRuleList[childIndex][subItem.name], rules: [{ required: true, message: `${subItem.placehold} 请勿输入空格`, pattern: /^[^\s]*$/ }] }
                      ]"
                      name="name"
                      :placeholder="subItem.placehold"
                      style="width: 200px"
                    />
                  </template>
                  <template v-if="subItem.formType == 'inputNumber'">
                    <a-input-number
                      v-decorator="[
                        `useRule[${childIndex}][${subItem.name}]`,
                        {
                          initialValue: useRuleList[childIndex][subItem.name],
                          rules: [{ required: subItem.options[0].max == 'Infinity' ? false : true, message: `${subItem.placehold}` }]
                        }
                      ]"
                      name="name"
                      :step="subItem.options[0].step"
                      :max="subItem.options[0].max == 'Infinity' ? Infinity : parseInt(subItem.options[0].max)"
                      :min="subItem.options[0].min"
                      :placeholder="subItem.placehold"
                      style="width: 200px"
                    />
                  </template>
                  <template v-if="subItem.formType == 'select'">
                    <a-select
                      v-decorator="[`useRule[${childIndex}][${subItem.name}]`, { initialValue: useRuleList[childIndex][subItem.name], rules: [{ required: true, message: `${subItem.placehold}` }] }]"
                      :placeholder="subItem.placehold"
                      style="width: 200px"
                      :getPopupContainer="triggerNode => triggerNode.parentNode"
                    >
                      <a-select-option :value="option.value" v-for="(option, optionIndex) in subItem.options" :key="optionIndex">
                        {{ option.label }}
                      </a-select-option>
                    </a-select>
                  </template>
                  <template v-if="subItem.formType == 'text'">
                    <div style="flex: 0 0 auto; white-space: nowrap">{{ subItem.placehold }}</div>
                  </template>
                </a-form-item>

                <div v-if="typeRules.type == 'dymic'" class="control">
                  <span v-if="childIndex == 0" class="add" @click="addRules">增加</span>
                  <span v-else class="remove" @click="removeRules(childIndex)">移除</span>
                </div>
              </div>
            </a-col>
          </a-row>
        </template>
        <!-- <a-form-item label="搭盒次数" v-if="showDahe" has-feedback>
          <a-input
            v-decorator="['valueDa', { rules: [{ required: true, pattern: /^[1-9]\d*$/, message: '请输入要盒次数' }] }]"
            name="name"
            placeholder="请输入"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="每月要盒数" v-if="showYaohe" has-feedback>
          <a-input
            v-decorator="['valueYao', { rules: [{ required: true, pattern: /^[1-9]\d*$/, message: '请输入要盒次数' }] }]"
            name="name"
            placeholder="请输入"
            autocomplete="off"
          />
        </a-form-item> -->
        <a-divider />

        <a-form-item label="展示名称" has-feedback>
          <a-input
            v-decorator="[
              'outName',
              {
                rules: [
                  {
                    required: false,
                    max: 20,
                    message: '请输入权益名称，不超过6个字符,不可输入符号！',
                    whitespace: true,
                    pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/
                  }
                ]
              }
            ]"
            name="outName"
            placeholder="请输入"
            :max-length="20"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="排序号" has-feedback>
          <a-input
            v-decorator="['sorted', { rules: [{ required: false, pattern: /^[1-9]\d*$/, message: '请输入顺序权重，数字越大越优！', whitespace: true }] }]"
            name="name"
            placeholder="请输入"
            autocomplete="off"
          />
        </a-form-item>
        <a-row class="link">
          <a-col :lg="5" :sm="7" style="text-align: right">
            <a-form-item label="链接" style="width: 100%" :labelCol="{ lg: { span: 24 }, sm: { span: 24 } }"></a-form-item>
          </a-col>
          <a-col :lg="10" :sm="17">
            <a-form-item has-feedback style="width: 100%" :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }">
              <a-input
                v-decorator="['actionName', { rules: [{ required: false, whitespace: true, message: '请输入行动点！', max: 40 }] }]"
                name="name"
                :max-length="40"
                placeholder="请输入链接标题"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item has-feedback style="width: 100%" :wrapperCol="{ lg: { span: 24 }, sm: { span: 24 } }">
              <a-input
                v-decorator="['actionUrl', { rules: [{ required: false, message: '请输入行动点链接,不允许输入中文！', whitespace: true, pattern: /^[^\u4e00-\u9fa5]{0,}$/ }] }]"
                name="name"
                placeholder="请输入链接http://"
                autocomplete="off"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <!-- <a-form-item label="行动点链接" has-feedback> </a-form-item> -->
        <a-form-item label="描述" has-feedback>
          <a-input
            v-decorator="[
              'label',
              {
                rules: [
                  {
                    required: false,
                    max: 100,
                    message: '请输入描述，不超过100个字符,不可输入符号！',
                    whitespace: true,
                    pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/
                  }
                ]
              }
            ]"
            name="label"
            placeholder="请输入描述"
            :max-length="100"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="介绍" has-feedback>
          <a-textarea rows="6" placeholder="请输入" :max-length="1000" v-decorator="['content', { rules: [{ required: false, max: 1000, message: '请输入介绍，不超过100个字符！' }] }]" />
        </a-form-item>

        <a-form-item label="图标">
          <a-upload
            v-decorator="['upload', { rules: [{ required: false, message: '请上传图标！' }] }]"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="https://up-z0.qiniup.com/"
            :before-upload="
              e => {
                beforeUpload(e, 'basePic')
              }
            "
            :data="formBasePicData"
            :headers="headers"
            @change="
              e => {
                handleChange(e, 'basePic')
              }
            "
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="icon-img" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
            <a-input v-decorator="['icon']" type="hidden" />
          </a-upload>
        </a-form-item>
        <a-form-item label="生日图标">
          <JImageUpload :uploadParams="getUploadParams()" :isMultiple="false" :accept="'image/*'" @fileChange="fileChange" v-model="imgList"></JImageUpload>
        </a-form-item>
        <a-form-item label="图片介绍">
          <a-upload
            v-decorator="['uploadMulti', { rules: [{ required: false, message: '请上传图片介绍！' }] }]"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            action="https://up-z0.qiniup.com/"
            :multiple="true"
            :show-upload-list="true"
            :before-upload="
              e => {
                beforeUpload(e, 'multiPic')
              }
            "
            :data="formMultiPicData"
            :headers="headers"
            :fileList="fileMultiPicList"
            @change="
              e => {
                handleChange(e, 'multiPic')
              }
            "
          >
            <div>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
            <a-input v-decorator="['detailImgs', {}]" type="hidden" />
          </a-upload>
        </a-form-item>
        <a-divider />
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary">提交</a-button>
          <a-button style="margin-left: 8px" @click="handleBack">取消</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>
<script>
import { rightsDetail, rightsCreate, rightConfigList } from '@/api/box/marketing'
import { cardList, goodsCardList } from '@/api/box/product'
import { uploadToken } from '@/api/api'
import { uploadImgHost } from '@/assets/js/common'
import globalData from '@/assets/js/common'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import pick from 'lodash.pick'
function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
export default {
  name: 'BaseForm',
  components: { JImageUpload },
  data() {
    return {
      spinning: true,
      uploadToken: '',
      goodsList: [],
      showDahe: false,
      showYaohe: false,
      form: this.$form.createForm(this),
      loading: false,
      imageUrl: '',
      formBasePicData: {
        token: '',
        key: ''
      },
      formMultiPicData: {
        token: '',
        key: ''
      },
      headers: {
        authorization: 'authorization-text'
      },
      fileMultiPicList: [],
      imgBaseUrl: '',
      rightId: null,
      rightConfig: [],
      typeRules: {
        children: []
      },
      useRuleList: [],
      formDetail: {},
      hasEffect: false,
      customStore: false,
      getStartDays: false,
      getEndDays: false,
      imgList: [],
      iconList: [],
      birthGif: ''
    }
  },
  watch: {},
  computed: {
    checkStoreType() {
      if (this.form.getFieldValue('suitableStoreType') == 3) {
        return true
      } else {
        return false
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  mounted() {
    this.imgBaseUrl = uploadImgHost
    this.fetchPathId()
  },
  methods: {
    async fetchPathId() {
      this.spinning = true
      this.goodsList = []
      await this.fetchUploadToken()
      await this.getRightConfigList()
      await this.fetchGoodsList()
      const id = this.$route.params.id
      if (id !== 'add') {
        this.rightId = id
        await this.fetchData(id)
      } else {
        this.useRuleList = []
        this.fileMultiPicList = []
        // this.form.getFieldDecorator('valueDa')
        // this.form.getFieldDecorator('valueYao')
        this.form.setFieldsValue({
          upload: '',
          uploadMulti: [],
          memberCardId: '',
          rightsType: '',
          name: '',
          outName: '',
          label: '',
          content: '',
          sorted: '',
          actionName: '',
          actionUrl: '',
          effectiveTime: '',
          // effectiveTimeNum: '',
          suitableStoreType: ''
          // endDrawTimeConfigNum: '',
          // endDrawTimeConfigType: '',
          // startDrawTimeConfigNum: '',
          // startDrawTimeConfigType: ''
          // valueDa: '',
          // valueYao: ''
        })
        this.imageUrl = ''
        // this.showDahe = false
        // this.showYaohe = false
        this.imgList = []
        this.spinning = false
      }
    },
    fetchUploadToken() {
      return uploadToken()
        .then(res => {
          if (res.code === 0) {
            this.uploadToken = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('fetchUploadToken:' + err)
        })
    },
    fetchGoodsList() {
      let params = {
        page: {
          pageNo: 1,
          pageSize: 100
        }
      }
      return cardList(params)
        .then(res => {
          if (res.code == 0) {
            this.goodsList = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('fetchGoodsList:' + err)
        })
    },
    fetchData(id) {
      let self = this
      const data = {
        requestData: {
          id: id
        }
      }
      return rightsDetail(data)
        .then(res => {
          // console.log(res)
          if (res.code === 0) {
            const data = res.data
            this.formDetail = res.data
            const multiPic = res.data.detailImgs
            this.fileMultiPicList = []
            if (multiPic !== undefined && multiPic !== null && multiPic !== '') {
              const multiPicArr = multiPic.split(',')
              for (let item in multiPicArr) {
                this.fileMultiPicList.push({
                  url: multiPicArr[item],
                  uid: multiPicArr[item],
                  name: multiPicArr[item],
                  status: 'done'
                })
              }
            }
            this.useRuleList = JSON.parse(data.useRule)
            // console.log(this.useRuleList)

            let result = this.rightConfig.filter(e => e.rightType == data.rightsType)
            if (result.length > 0) {
              this.typeRules = result[0]

              if (this.useRuleList && this.useRuleList.length > 1) {
                let child = this.typeRules.children[0]
                let arr = []
                for (let i = 0; i < this.useRuleList.length; i++) {
                  /* let item = this.useRuleList[i]
                Object.keys(item).forEach(e => {
                  for (let son of child) {
                    if (son.name == e) {
                      son.value = item[e]
                    }
                  }
                }) */
                  arr.push(child)
                }
                this.typeRules.children = arr
              }
              // console.log(this.typeRules)
            }
            if (data.rightsType == 6) {
              this.$nextTick(() => {
                self.form.setFieldsValue({
                  endDrawTimeConfigType: data.endDrawTimeConfigType,
                  startDrawTimeConfigType: data.startDrawTimeConfigType
                })
              })
              if (data.startDrawTimeConfigType == 1) {
                this.getStartDays = true
                this.$nextTick(() => {
                  self.form.setFieldsValue({
                    startDrawTimeConfigNum: parseInt(data.startDrawTimeConfigNum)
                  })
                })
              }
              if (data.endDrawTimeConfigType == 1) {
                this.getEndDays = true
                this.$nextTick(() => {
                  self.form.setFieldsValue({
                    endDrawTimeConfigNum: parseInt(data.endDrawTimeConfigNum)
                  })
                })
              }
            }
            if (data.suitableStoreType == 4) {
              this.customStore = true
              this.$nextTick(() => {
                self.form.setFieldsValue({
                  storeIds: data.storeIds ? data.storeIds.join(',') : '',
                  isStoreId: data.isStoreId
                })
              })
            }
            if (data.effectiveTimeNum > 0) {
              this.hasEffect = true
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  effectiveTime: 1,
                  effectiveTimeNum: data.effectiveTimeNum
                })
              })
            } else {
              this.hasEffect = false
              this.form.setFieldsValue({
                effectiveTime: 0
                // effectiveTimeNum: data.effectiveTimeNum
              })
            }
            this.$nextTick(() => {
              setTimeout(() => {
                self.form.setFieldsValue(
                  pick(data, 'upload', 'uploadMulti', 'memberCardId', 'rightsType', 'name', 'outName', 'label', 'content', 'sorted', 'actionName', 'actionUrl', 'suitableStoreType')
                )
              })
            })
            this.imgList = data.birthGif?[data.birthGif]:[]
            this.imageUrl = data.icon
            this.spinning = false
          } else {
            this.spinning = false
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('rightsDetail:' + err)
        })
    },
    // handler
    handleSelectChange(value) {
      console.log(value)
      let result = this.rightConfig.filter(e => e.rightType == value)
      this.typeRules = result[0]
      console.log(this.typeRules)
      let item = {}
      let arr = this.typeRules.children[0]
      for (let i of arr) {
        let name = i.name
        item[name] = ''
      }
      console.log(item)
      this.useRuleList = []
      this.useRuleList.push(item)
    },
    handleBirthdayChange(value, type) {
      switch (type) {
        case 'start':
          this.getStartDays = false
          if (value == 1) this.getStartDays = true
          break
        case 'end':
          this.getEndDays = false
          if (value == 1) this.getEndDays = true
          break
      }
    },
    handleEffectChange(value) {
      this.hasEffect = false
      if (value == 1) {
        this.hasEffect = true
      }
    },
    handleStoreChange(value) {
      this.customStore = false
      if (value == 4) {
        this.customStore = true
      }
    },
    handleChange(info, type) {
      switch (type) {
        case 'basePic':
          getBase64(info.file.originFileObj, imageUrl => {
            this.imageUrl = imageUrl
          })
          if (info.file.status === 'done') {
            const imgUrl = info.fileList[info.fileList.length - 1]
            this.form.setFieldsValue({
              icon: this.imgBaseUrl + imgUrl.response.key
            })
          }
          break
        case 'multiPic':
          let fileList = [...info.fileList]
          if (fileList.length > 10) {
            this.$message.warning('最多上传10张！')
            return false
          }
          if (info.file.status === 'error') {
            this.$message.error(`${info.file.name} 上传失败.`)
          } else {
            fileList = fileList.map(file => {
              if (file.response) {
                file.url = this.imgBaseUrl + file.response.key
                console.log('上传成功', file.response)
              }
              return file
            })
            this.fileMultiPicList = fileList
            const MultiPics = this.fileMultiPicList.map(item => item.url).join(',')
            this.form.setFieldsValue({ detailImgs: MultiPics })
          }

          break
      }
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    fileChange(list) {
      console.log(list)
      if (list.length > 0) this.birthGif = list[0].url
    },
    beforeUpload(file, type) {
      // console.log(file, type)
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5
      return new Promise((resolve, reject) => {
        if (!isJpgOrPng) {
          this.$message.error('请上传JPG或PNG格式!')
          reject(file)
        }
        if (!isLt2M) {
          this.$message.error('图片大小请小于5MB!')
          reject(file)
        } else {
          console.log('******IMG校验通过*******')
          const key = new Date().getTime() + '-' + file.name
          switch (type) {
            case 'basePic':
              this.formBasePicData.key = key
              this.formBasePicData.token = this.uploadToken

              break
            case 'multiPic':
              this.formMultiPicData.key = key
              this.formMultiPicData.token = this.uploadToken
              break
          }
          resolve(file)
        }
      })
    },

    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const data = values
          delete data.upload
          delete data.uploadMulti

          data.useRule = JSON.stringify(data.useRule)
          if (data.outName == '' || data.outName == null) {
            data.outName = data.name
          }
          if (data.storeIds != null && data.storeIds != undefined) {
            data.storeIds = data.storeIds.split(',')
            data.storeIds = data.storeIds.map(e => e.trim())
          }
          if (data.effectiveTime == 0) {
            data.effectiveTimeNum = 0
          }
          delete data.effectiveTime
          data.birthGif = this.birthGif
          console.log(data)
          this.submitCreate(data)
        }
      })
    },
    submitCreate(d) {
      const data = {
        requestData: d
      }
      if (this.rightId !== 'add') {
        data.requestData.id = this.rightId
      } else {
        delete data.requestData.id
      }
      rightsCreate(data)
        .then(res => {
          // console.log(res)
          if (res.code === 0) {
            this.$message.success(res.msg)
            this.$router.push('/box/operations/rights/list')
          }
        })
        .catch(err => {
          console.log('submitCreate:' + err)
        })
    },
    handleBack() {
      this.$router.go(-1)
    },
    getRightConfigList() {
      return rightConfigList().then(res => {
        if (res.code == 0) {
          this.rightConfig = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    addRules() {
      let rule = this.typeRules.children[0]
      this.typeRules.children.push(rule)
      console.log(this.typeRules, this.useRuleList)
      let arr = JSON.parse(JSON.stringify(this.useRuleList[0]))
      Object.keys(arr).forEach(e => {
        arr[e] = ''
      })
      this.useRuleList.push(arr)
    },
    removeRules(index) {
      this.useRuleList = this.form.getFieldValue('useRule')
      this.typeRules.children.splice(index, 1)
      this.useRuleList.splice(index, 1)
      console.log(index, this.typeRules, this.useRuleList)
      // 初始化initialValue
      this.form.resetFields(['useRule'])
    }
  }
}
</script>
<style scoped>
.icon-img {
  width: 86px;
  height: 86px;
  object-fit: scale-down;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  /* font-size: 32px; */
  /* color: #999; */
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  /* font-size: 32px; */
  /* color: #999; */
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
<style lang="less" scoped>
.rules-package {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  > div {
    margin-right: 8px;
  }
  .control {
    flex: 0 0 auto;
    color: #1890ff;
    cursor: pointer;
    margin-bottom: 24px;
    margin-left: 16px;
  }
}
.link {
  .ant-col {
    label::after {
      content: ':';
      position: relative;
      top: -0.5px;
      margin: 0 8px 0 2px;
    }
    /deep/ .ant-form-item {
      width: 100%;
    }
  }
}
</style>

